package com.andova.handler

import android.os.Handler
import android.os.Message
import com.andova.ext.aw

class SignalHandler : Handler() {
    companion object {
        const val SIGNAL_WHAT_DEFAULT = 1
    }

    private val signalMap = mutableMapOf<Int, Boolean>()

    @Suppress("MemberVisibilityCanBePrivate")
    fun obtain(what: Int = SIGNAL_WHAT_DEFAULT): Boolean = signalMap[what] ?: false
    fun load(delayMillis: Long = 30000L, what: Int = SIGNAL_WHAT_DEFAULT): Boolean {
        if (obtain(what)) return true
        signalMap[what] = true
        sendEmptyMessageDelayed(what, delayMillis)
        return false
    }

    fun signal(delayMillis: Long = 30000L, what: Int = SIGNAL_WHAT_DEFAULT) {
        removeCallbacksAndMessages(null)
        sendEmptyMessageDelayed(what, delayMillis)
    }

    fun release(what: Int = SIGNAL_WHAT_DEFAULT) {
        signalMap[what] = false
    }

    override fun handleMessage(msg: Message) {
        aw("signal what:${msg.what} locked exception, release it")
        signalMap[msg.what] = false
    }
}